package com.example.demo.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Component
@ConfigurationProperties(prefix = "web")
public class UploadFile {


    static String uploadFilePath;
    @Value("${web.upload-path}")
    public void setUploadFilePath(String s){
        uploadFilePath = s;
    }

    /**
     * 根据 MultipartFile 文件上传到服务器，返回地址
     * @param file
     * @return path 图片地址
     */
    public static String uploadByMultipartFile(MultipartFile file) throws IOException {
        if(file.isEmpty()) {
            return "";
        }
        System.out.println("文件上传路径：" + uploadFilePath);
        String fileName = file.getOriginalFilename();  // 文件名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
        fileName = UUID.randomUUID() + suffixName; // 新文件名
        String path = "/upload/images/" + uploadFilePath + fileName;
        File dest = new File(path);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        file.transferTo(dest);
        return path;
    }

}
